﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using KandaAlpha.UI.Mvc.Infrastructure.Mvc;
using KandaAlpha.Application.Interfaces;
using KandaAlpha.Domain.Model.Entities;
using KandaAlpha.Domain.Model.ValueObjects;
using KandaAlpha.UI.Mvc.Models; 

namespace KandaAlpha.UI.Mvc.Controllers
{
    [HandleError]
    public class HomeController : ControllerAppBase
    {

        public HomeController(IApplicationService appService) : base(appService)
        {
            Model = CreateViewData<HomeViewData>(); 
        }

        protected HomeViewData Model
        {
            get
            {
                return ViewData.Model as HomeViewData; 
            }
            set
            {
                ViewData.Model = value; 
            }
        }

        public ActionResult Index()
        {
            Model.Title = "Welcome to KandaAlpha, powered by ASP.NET MVC and db4o";


            using (var uow = UnitOfWorkFactory.Create())
            {

                // use a specific method on customer service
                var kp = CustomerService.GetBestCustomer();

                if (kp != null) // update the customer record
                {
                    kp.Timestamp.LastModifiedOn = DateTime.Now;
                }
                else // make a new customer
                {
                    kp = new Customer() { 
                        FirstName = "Keith", 
                        LastName = "Patton", 
                        ID = 1, 
                        Timestamp = new Timestamp() {
                            CreatedOn = DateTime.Now, 
                            LastModifiedOn = DateTime.Now } 
                        };
                    CustomerService.Add(kp);
                }

                // commit the unit of work
                uow.Commit();
            }

            // return all customers 
            Model.Customers = CustomerService.GetAll();

            return View();
        }


        public ActionResult About()
        {
            return View();
        }
    }
}
